<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
       div{
           width: 400px;
           height: 200px;
           border:1px red solid;
           position: absolute;
           left:100px;
           top:100px;
       }
    
    </style>

</head>
<body>
        <div></div>
     
</body>
</html>
<script src='../js/Util.js'></script>
<script>

//获得div的对象
let divObj = document.getElementsByTagName('div')[0];
//保存鼠标按下的状态
let ismove=false;

//绑定鼠标移动事件
divObj.onmousemove=(e)=>{
    //判断是否可以移动
    if(ismove){
        //获得事件对象
        let eventObj = window.event||e;
            //获得鼠标相对于客户可视区域的坐标
            let cx = eventObj.clientX;
            let cy = eventObj.clientY;
            //获得div元素的高和框
            let w = parseInt(getStyle(divObj,'width'));
            let h = parseInt(getStyle(divObj,'height'));
            //设置div的位置 ，减去w/2和h/2是为 把鼠标设置在中间
            divObj.style.left=(cx-w/2)+'px';
            divObj.style.top=(cy-h/2)+'px';
    } 
}

//事件按下事件

divObj.onmousedown=()=>{
     ismove=true;
}

</script>